import time

from selenium import webdriver
from selenium.common import WebDriverException, NoSuchElementException, InvalidArgumentException, TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from functions import open_browser


class Base:
    def __init__(self, browser):
        self.driver = browser

    def get(self, url):
        try:
            self.driver.get(url)
        except (WebDriverException, InvalidArgumentException):
            print("输入的网址不正确")

    # 元素定位
    def find_element(self, locator,timeout=5):  # locator 元组
        try:
            return WebDriverWait(self.driver,timeout).until(EC.presence_of_element_located(locator))
        except TimeoutException:
            print("元素定位失败")

    def click(self, locator):
        element = self.find_element(locator)
        if element is not None:
            element.click()
        else:
            print("元素定位失败")

    def send_keys(self, locator, text):
        pass

    def get_attribute(self, locator, attr):
        # 获取元素属性
        element = self.find_element(locator)
        if element:
            return element.get_attribute(attr)

    def get_element_text(self, locator):
        # 获取元素文本
        element = self.find_element(locator)
        if element:
            return element.text

    def quit(self, seconds=3):
        time.sleep(seconds)
        self.driver.quit()


if __name__ == '__main__':
    browser = open_browser()
    base = Base(browser)
    base.get("https://www.baidu.com")
    kw = base.find_element((By.ID, "kw"),3)
    print(kw.get_attribute("outerHTML"))
    base.quit()
